package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.annotation.Incomplete;
import org.aeon.constant.GroupDisplayType;
import org.aeon.entity.dto.ChatGroupDto;
import org.aeon.message.request.GroupsListRequestMessage;
import org.aeon.message.response.GroupsListResponseMessage;
import org.aeon.service.ChatGroupService;
import org.aeon.service.UserGroupRelationService;
import org.aeon.service.factory.ChatGroupServiceFactory;
import org.aeon.service.factory.UserGroupRelationServiceFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: MissingAeon
 * @date: 2024/2/19 14:06
 * @description: 组列表请求处理程序
 */
@Slf4j
@ChannelHandler.Sharable
@Incomplete
public class GroupsListRequestHandler extends SimpleChannelInboundHandler<GroupsListRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupsListRequestMessage msg) throws Exception {
        final GroupsListResponseMessage resMsg = new GroupsListResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final Long userId = msg.getUserId();
        // 获取创建的
        final ChatGroupService groupService = ChatGroupServiceFactory.getService();
        Map<GroupDisplayType, List<ChatGroupDto>> map = new HashMap<>(2);
        // 管理的群聊
        final List<ChatGroupDto> groups = groupService.getGroupsByUserId(userId);
        map.put(GroupDisplayType.CREATED, groups);
        // 加入的群聊
        final UserGroupRelationService groupRelationService = UserGroupRelationServiceFactory.getService();
        final List<Long> groupIds = new ArrayList<>(groupRelationService.getGroups(userId));
        // 去除相交
        groups.stream().map(ChatGroupDto::getId).forEach(groupIds::remove);
        // 查询群名称
        final List<ChatGroupDto> groups2 = groupService.getGroupsByIds(groupIds);

        map.put(GroupDisplayType.JOINED, groups2);
        resMsg.setResponse(true, "查询成功");
        resMsg.setMap(map);
        ctx.writeAndFlush(resMsg);
    }
}
